<template>
  <div class="search">
    <!-- 头部 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索 -->
    <!-- search事件在移动端上就是点击了搜索(确认)按钮，pc上敲回车键 -->
    <van-search
      v-model.trim="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch(value)"
      shape="round"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>
    <!-- 推荐 -->
    <van-cell-group v-if="value">
      <!-- :title="highLight(item,keyword) span不能被识别" -->
      <van-cell
        icon="search"
        v-for="(item, index) in sugList"
        :key="index"
        @click="onSearch(item)"
      >
        <span v-html="highLight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        :title="item"
        v-for="(item, i) in history"
        :key="i"
        @click="onSearch(item)"
      >
        <van-icon name="close" @click.stop="del(item)" />
      </van-cell>
    </van-cell-group>
    <!-- 提示 -->
    <van-empty
      v-show="value && sugList.length === 0"
      class="custom-image"
      image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
      description="暂无结果"
    />
  </div>
</template>

<script>
import {
  setStorageSearchHistory,
  getStorageSearchHistory
} from '@/utils/storage'
import { getSuggest } from '@/api/search'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      sugList: [],
      // 最新的在最前面，数组里不能有重复的(先删后加)
      history: getStorageSearchHistory()
    }
  },
  methods: {
    // 高亮
    highLight(str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(
        reg,
        (item) => `<span style="color: red;">${item}</span>`
      )
    },
    onInput() {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (!this.value) return
        const res = await getSuggest(this.value)
        console.log(res)

        // 处理没有数据的情况
        if (res.data.options[0] === null) return (this.sugList = [])

        this.sugList = res.data.options
      }, 500)
    },
    onSearch(item) {
      console.log(item)
      if (!item) return this.$toast('请输入内容')
      // 先删
      this.history = this.history.filter((v) => v !== item)
      // 后加
      this.history.unshift(item)
      // 存到本地
      setStorageSearchHistory(this.history)
      // 跳转页面
      this.$router.push({
        path: '/search/result',
        query: {
          // 通过query来携带参数
          keyword: item
        }
      })
    },
    del(item) {
      // 删除历史记录
      this.history = this.history.filter((v) => v !== item)
      // 存到本地
      setStorageSearchHistory(this.history)
    }
  }
}
</script>

<style lang="less" scoped>
.custom-image .van-empty__image {
  width: 90px;
  height: 90px;
}
</style>
